What does % mean in Java

In this post, we will be learning about the percent sign in Java. In simple words, for positive numbers, modulus operator(%) means percent sign in the java programming language.

Read Also: What does \n and \t mean in Java

What is the modulus operator?

The modulus operator in java returns the remainder from division.
For example:
1. int remainder = 14 % 3
2. int quotient = 14 / 3
The first operator modulus results in 2 whereas the second operator division(/) results in 4.
In other words, x = A%B means that x will contain the value of the remainder when dividing A by B.

More examples:
 15%8 = 7,
13%7 = 6,
15%5 = 0

Java Program Example

 public class PercentSignJava {
    public static void main(String args[]) {
      System.out.println("Modulus operator examples:");         
      int a=20, b=7;
      int z = a%b;
      System.out.println("integer example: 20%7 = " + z);
      float c= 5.5f, d=2.5f;
      float y = c%d;
      System.out.println("float example: 5.5%2.5 = " + y);
    }
}

Output:
Modulus operator examples:
integer example: 20%7 = 6
float example: 5.5%2.5 = 0.5


What if the input number is negative

Note: If the input number is negative, then the modulus always returns positive results whereas the remainder may give negative results.

Source: Stackoverflow

Where modulus operator can be useful

The modulus operator can be used in the following ways:

1. You can check whether one number is divisible by another, for example, if a % b is zero then a is divisible by b.
2. You can extract the rightmost digit or digits from a number. for example, a % 10 returns the rightmost digit of a (in base 10). Similarly, a % 100 returns the last two digits.

That's all for today, please mention in the comments in case you have any questions related to percent sign in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry